package com.software.sqlite.api.app.v1.service.impl;

import com.alibaba.fastjson.JSON;
import com.software.sqlite.api.app.v1.service.IMovieV1Service;
import com.software.sqlite.api.app.v1.vo.AppV1Result;
import com.software.sqlite.common.CommonContant;
import com.software.sqlite.entity.*;
import com.software.sqlite.mapper.*;
import com.software.sqlite.service.impl.TbMovieUserService;
import com.software.sqlite.service.impl.YstMovieService;
import com.software.sqlite.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

@Service
@Slf4j
public class MovieV1Service implements IMovieV1Service {


    @Resource
    private TbAndroidDeviceMapper androidDeviceMapper;
    @Resource
    private TbSailastvClientMapper sailastvClientMapper;
    @Resource
    private TbMovieUserService movieUserService;
    @Resource
    private TbMovieUserMapper movieUserMapper;
    @Resource
    private TbMovieMapper movieMapper;
    @Resource
    private TbProductInfoMapper productInfoMapper;
    @Resource
    private TbMovieServerMapper movieServerMapper;
    @Resource
    private TbMovieUserBillMapper movieUserBillMapper;
    @Resource
    private TbMovieWatchRecordMapper movieWatchRecordMapper;
    @Resource
    private TbMovieLikeRecordMapper movieLikeRecordMapper;
    @Resource
    private TbMovieCollectRecordMapper movieCollectRecordMapper;
    @Resource
    private HttpServletRequest request;
    @Resource
    private YstMovieService ystMovieService;
    @Value("${file.film.dangjian}")
    private String dangjianDir;
    @Value("${file.film.zongyi}")
    private String zongyiDir;
    @Value("${file.film.movie}")
    private String movieDir;

    @Override
    public synchronized AppV1Result register(String userName, String password,String mobile,String idCard,String verifyCode,Long shipId,String uuid) {
        AppV1Result result=new AppV1Result();
        try {
            if(CommonUtils.isBlank(userName)){
                result.setSuccess(false);
                result.setErrMsg("账号不能为空");
                return result;
            }
            if(CommonUtils.isBlank(password)){
                result.setSuccess(false);
                result.setErrMsg("密码不能为空");
                return result;
            }
            if(CommonUtils.isBlank(mobile)){
                result.setSuccess(false);
                result.setErrMsg("手机号码不能为空");
                return result;
            }
            if(CommonUtils.isBlank(idCard)){
                result.setSuccess(false);
                result.setErrMsg("身份证不能为空");
                return result;
            }
            if(CommonUtils.isBlank(verifyCode)){
                result.setSuccess(false);
                result.setErrMsg("验证码不能为空");
                return result;
            }
            if(CommonUtils.isBlank(uuid)){
                result.setSuccess(false);
                result.setErrMsg("设备uuid不能为空");
                return result;
            }
            String key="reg_verifyCode_"+uuid;
            String code=CommonUtils.parseStringData(HutoolCacheUtils.get(key),"regCodeError");
            log.info(key+":"+code+",verifyCode:"+verifyCode);
            if(!code.equals(verifyCode)) {
                result.setSuccess(false);
                result.setErrMsg("验证码错误");
                return result;
            }
            log.info("uuid=="+uuid);
            TbMovieUser movieUser= movieUserMapper.selectByUserName(userName);
            if(movieUser!=null){
                result.setSuccess(false);
                result.setErrMsg("账号已存在");
                return result;
            }
            movieUser= movieUserMapper.selectByMobile(mobile);
            if(movieUser!=null){
                result.setSuccess(false);
                result.setErrMsg("手机号已存在");
                return result;
            }
            movieUser= movieUserMapper.selectByMobile(idCard);
            if(movieUser!=null){
                result.setSuccess(false);
                result.setErrMsg("身份证已存在");
                return result;
            }

            TbMovieServer movieServer = new TbMovieServer();
            List<TbMovieServer> list = movieServerMapper.selectListBySQL(movieServer);
            if (list.size() == 0) {
                result.setSuccess(false);
                result.setErrMsg("服务器配置异常，请联系管理员");
                return result;
            }

            TbMovieUser model=new TbMovieUser();
            model.setMovieUserId(CommonUtils.parseLongData(DateUtils.format(new Date(),DateUtils.YMD_DASH_WITH_TIME_STR)));
            model.setShipId(CommonUtils.parseLongData(list.get(0).getShipId()));
            model.setShipName(list.get(0).getShipName());
            model.setUserName(userName);
            model.setNickname(userName);
            model.setTrueName(userName);
            model.setPassword(password);
            model.setMobile(mobile);
            model.setIdCard(idCard);
            model.setUserToken(UUID.randomUUID().toString().toUpperCase());
            model.setWalletAmount(BigDecimal.ZERO);
            model.setSex("1");
            model.setUserStatus("open");
            model.setUseStatus("normal");
            model.setCreateAdminId(0L);
            model.setCreateTime(new Date());
            movieUserMapper.insert(model);
            result.setSuccess(true);
            result.setErrMsg("");
        }catch (Exception e){
            e.printStackTrace();
            result.setErrMsg("程序异常");
        }
        return result;
    }

    @Override
    public AppV1Result login(String userName, String password,String verifyCode,String uuid) {
        AppV1Result result=new AppV1Result();
        try {
            if(CommonUtils.isBlank(uuid)){
                result.setSuccess(false);
                result.setErrMsg("设备uuid不能为空");
                return result;
            }
            if(CommonUtils.isBlank(userName)){
                result.setSuccess(false);
                result.setErrMsg("账号不能为空");
                return result;
            }
            if(CommonUtils.isBlank(password)){
                result.setSuccess(false);
                result.setErrMsg("密码不能为空");
                return result;
            }
            if(CommonUtils.isBlank(verifyCode)){
                result.setSuccess(false);
                result.setErrMsg("验证码不能为空");
                return result;
            }
            String key="login_verifyCode_"+uuid;
            String code=CommonUtils.parseStringData(HutoolCacheUtils.get(key),"loginCodeError");
            log.info(key+":"+code+",verifyCode:"+verifyCode);
            if(!code.equals(verifyCode)) {
                result.setSuccess(false);
                result.setErrMsg("验证码错误");
                return result;
            }
            TbMovieUser movieUser=movieUserMapper.selectByLogin(userName,password);
            if(movieUser==null){
                result.setSuccess(false);
                result.setErrMsg("账号或密码不正确");
                return result;
            }
            result.setSuccess(true);
            result.setErrMsg("");
            result.setData(movieUser);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public AppV1Result myInfo(String uuid,String userToken)
    {
        AppV1Result result=new AppV1Result();
        try {
            if(CommonUtils.isBlank(uuid)){
                result.setSuccess(false);
                result.setErrMsg("设备uuid不能为空");
                return result;
            }
            TbMovieUser movieUser=movieUserMapper.myInfo(userToken);
            if(movieUser==null){
                result.setSuccess(false);
                result.setErrMsg("用户参数不正确");
                return result;
            }
            result.setSuccess(true);
            result.setErrMsg("");
            result.setData(movieUser);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public void showZongyi(String movieId, HttpServletResponse response)throws Exception
    {
        try{
            TbMovie movie=movieMapper.selectMovieByMovieId(movieId,"");
            String videoFileName="";
            if(movie!=null){
                videoFileName=movie.getFileName();
                String path = request.getContextPath();
                String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
                response.setCharacterEncoding("utf-8");
                response.setContentType("text/html");
                PrintWriter out = response.getWriter();
                out.write("<style>body{background-color: rgb(0, 0, 0);}</style><video controls autoplay muted name=\"media\"style=\"    position: absolute;\n" +
                        "    top: 0px;\n" +
                        "    right: 0px;\n" +
                        "    bottom: 0px;\n" +
                        "    left: 0px;\n" +
                        "    max-height: 100%;\n" +
                        "    max-width: 100%;\n" +
                        "    margin: auto;\" ><source src=\""+basePath+"/admin/v1/common/downloadVideo?videoFileName="+videoFileName+"\" type=\"video/mp4\"></video>");
                out.close();
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void showDangjian(String movieId, HttpServletResponse response)throws Exception
    {
        try{
            TbMovie movie=movieMapper.selectMovieByMovieId(movieId,"");
            String videoFileName="";
            if(movie!=null){
                videoFileName=movie.getFileName();
                String path = request.getContextPath();
                String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
                response.setCharacterEncoding("utf-8");
                response.setContentType("text/html");
                PrintWriter out = response.getWriter();
                out.write("<style>body{background-color: rgb(0, 0, 0);}</style><video controls autoplay muted name=\"media\"style=\"    position: absolute;\n" +
                        "    top: 0px;\n" +
                        "    right: 0px;\n" +
                        "    bottom: 0px;\n" +
                        "    left: 0px;\n" +
                        "    max-height: 100%;\n" +
                        "    max-width: 100%;\n" +
                        "    margin: auto;\" ><source src=\""+basePath+"/admin/v1/common/downloadVideo?videoFileName="+videoFileName+"\" type=\"video/mp4\"></video>");
                out.close();
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void downloadDangjian(String movieId, HttpServletResponse response)throws Exception
    {
        try{
            TbMovie movie=movieMapper.selectMovieByMovieId(movieId,"");
            if(movie!=null){
                String filePath = dangjianDir+ File.separator+movie.getFileName();
                File file = new File(filePath);
                if (!file.exists()||!file.getName().endsWith(".mp4")) {
                    response.getOutputStream().close();
                    return;
                }
                String range = request.getHeader("Range");
                log.info("Range:" + range);
                if (range != null && range.length() > 7) {
                    log.info("该请求符合断点续传");
                    range = range.substring(6);
                    String[] arr = range.split("-");
                    long lenStart = Long.parseLong(arr[0]);
                    long end=0;
                    if (arr.length > 1) {
                        end = Long.parseLong(arr[1]) ;
                    }
                    long contentLength=end>0?(end-(lenStart-1)):(file.length()-(lenStart>0?lenStart-1:0));//如果指定范围，就返回范围数据长度，如果没有就返回剩余全部长度
                    response.setHeader("Content-Length", String.valueOf(contentLength));
//            response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");//加上会报错，不能用中文
                    response.setHeader("Content-Range", "bytes " + lenStart + "-" + (end>0?end:(file.length() - 1)) + "/" + file.length());
                    response.setContentType("video/mp4");
                    response.setHeader("Accept-Ranges", "bytes");
                    response.setStatus(HttpStatus.PARTIAL_CONTENT.value());//响应码206表示响应内容为部分数据，需要多次请求
                    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
                    randomAccessFile.seek(lenStart);//设置读取的开始字节数
                    if(end>0){//客户端指定了范围的数据，那就只给范围数据
                        int size= (int) (end-lenStart+1);
                        byte[] buffer = new byte[size];
                        int len = randomAccessFile.read(buffer);
                        if (len != -1) {
                            response.getOutputStream().write(buffer, 0, len);
                        }
                    }else{//没有指定范围
                        //视频每次返回一兆数据
                        int size = 1048576;//1MB
                        byte[] buffer = new byte[size];
                        int len ;
                        while ((len = randomAccessFile.read(buffer)) != -1) {
                            response.getOutputStream().write(buffer, 0, len);
                        }
                    }
                    randomAccessFile.close();
                }else{
                    log.info("该请求不符合断点续传");
                    response.setHeader("Content-Disposition", "attachment; filename=\"" +System.currentTimeMillis()+".mp4" + "\"");//不能用中文
                    response.setHeader("Content-Length", String.valueOf(file.length()-1));
                    response.setHeader("Content-Range", "" + (file.length()-1));
                    response.setHeader("Accept-Ranges", "bytes");
                    InputStream inStream=new FileInputStream(file);
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = inStream.read(buffer)) != -1) {
                        response.getOutputStream().write(buffer, 0, len);
                    }
                    inStream.close();
                }
                response.getOutputStream().flush();
                response.getOutputStream().close();
            }

        }catch (Exception e){
            log.error(e.getMessage());
        }
    }

    @Override
    public void downloadZongyi(String movieId, HttpServletResponse response)throws Exception
    {
        try{
            TbMovie movie=movieMapper.selectMovieByMovieId(movieId,"");
            if(movie!=null){
                String filePath = zongyiDir+ File.separator+movie.getFileName();
                File file = new File(filePath);
                if (!file.exists()||!file.getName().endsWith(".mp4")) {
                    response.getOutputStream().close();
                    return;
                }
                String range = request.getHeader("Range");
                log.info("Range:" + range);
                if (range != null && range.length() > 7) {
                    log.info("该请求符合断点续传");
                    range = range.substring(6);
                    String[] arr = range.split("-");
                    long lenStart = Long.parseLong(arr[0]);
                    long end=0;
                    if (arr.length > 1) {
                        end = Long.parseLong(arr[1]) ;
                    }
                    long contentLength=end>0?(end-(lenStart-1)):(file.length()-(lenStart>0?lenStart-1:0));//如果指定范围，就返回范围数据长度，如果没有就返回剩余全部长度
                    response.setHeader("Content-Length", String.valueOf(contentLength));
//            response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");//加上会报错，不能用中文
                    response.setHeader("Content-Range", "bytes " + lenStart + "-" + (end>0?end:(file.length() - 1)) + "/" + file.length());
                    response.setContentType("video/mp4");
                    response.setHeader("Accept-Ranges", "bytes");
                    response.setStatus(HttpStatus.PARTIAL_CONTENT.value());//响应码206表示响应内容为部分数据，需要多次请求
                    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
                    randomAccessFile.seek(lenStart);//设置读取的开始字节数
                    if(end>0){//客户端指定了范围的数据，那就只给范围数据
                        int size= (int) (end-lenStart+1);
                        byte[] buffer = new byte[size];
                        int len = randomAccessFile.read(buffer);
                        if (len != -1) {
                            response.getOutputStream().write(buffer, 0, len);
                        }
                    }else{//没有指定范围
                        //视频每次返回一兆数据
                        int size = 1048576;//1MB
                        byte[] buffer = new byte[size];
                        int len ;
                        while ((len = randomAccessFile.read(buffer)) != -1) {
                            response.getOutputStream().write(buffer, 0, len);
                        }
                    }
                    randomAccessFile.close();
                }else{
                    log.info("该请求不符合断点续传");
                    response.setHeader("Content-Disposition", "attachment; filename=\"" +System.currentTimeMillis()+".mp4" + "\"");//不能用中文
                    response.setHeader("Content-Length", String.valueOf(file.length()-1));
                    response.setHeader("Content-Range", "" + (file.length()-1));
                    response.setHeader("Accept-Ranges", "bytes");
                    InputStream inStream=new FileInputStream(file);
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = inStream.read(buffer)) != -1) {
                        response.getOutputStream().write(buffer, 0, len);
                    }
                    inStream.close();
                }
                response.getOutputStream().flush();
                response.getOutputStream().close();
            }

        }catch (Exception e){
            log.error(e.getMessage());
        }
    }

    @Override
    public AppV1Result dangjianList(String keyWord,String uuid,String userToken) {
        AppV1Result result=new AppV1Result();
        try {
            if(CommonUtils.isBlank(uuid)){
                result.setSuccess(false);
                result.setErrMsg("设备uuid不能为空");
                return result;
            }
//            TbMovieUser user=movieUserMapper.selectByUserToken(userToken);
//            if(user==null){
//                result.setSuccess(false);
//                result.setErrMsg("用户参数不正确");
//                return result;
//            }
            TbMovie model=new TbMovie();
            if(CommonUtils.isNotBlank(keyWord)){
                model=JSON.parseObject(keyWord,TbMovie.class);
            }
            List<TbMovie> movieList=movieMapper.selectDangjianList(userToken,model.getMovieUrl());
            if(movieList.size()>0)
            {
                for(TbMovie item:movieList){
                    item.setPosterLocalImg("../../../static/images/movie/default.jpg");
                }
            }
            result.setSuccess(true);
            result.setErrMsg("");
            result.setData(movieList);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public AppV1Result zongyiList(String keyWord,String uuid,String userToken) {
        AppV1Result result=new AppV1Result();
        try {
            if(CommonUtils.isBlank(uuid)){
                result.setSuccess(false);
                result.setErrMsg("设备uuid不能为空");
                return result;
            }
//            TbMovieUser user=movieUserMapper.selectByUserToken(userToken);
//            if(user==null){
//                result.setSuccess(false);
//                result.setErrMsg("用户参数不正确");
//                return result;
//            }
            TbMovie model=new TbMovie();
            if(CommonUtils.isNotBlank(keyWord)){
                model=JSON.parseObject(keyWord,TbMovie.class);
            }
            List<TbMovie> movieList=movieMapper.selectZonyiList(userToken,model.getMovieUrl());
            if(movieList.size()>0)
            {
                for(TbMovie item:movieList){
                    item.setPosterLocalImg("../../../static/images/movie/default.jpg");
                }
            }
            result.setSuccess(true);
            result.setErrMsg("");
            result.setData(movieList);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }


    @Override
    public AppV1Result movieList(String keyWord,String uuid,String userToken,boolean needLogin) {
        AppV1Result result=new AppV1Result();
        try {
            if(CommonUtils.isBlank(uuid)){
                result.setSuccess(false);
                result.setErrMsg("设备uuid不能为空");
                return result;
            }
//            TbMovieUser user=movieUserMapper.selectByUserToken(userToken);
//            if(user==null){
//                result.setSuccess(false);
//                result.setErrMsg("用户参数不正确");
//                return result;
//            }
            TbMovie model=new TbMovie();
            if(CommonUtils.isNotBlank(keyWord)){
                model=JSON.parseObject(keyWord,TbMovie.class);
            }
            List<TbMovie> movieList=movieMapper.selectMovieList(userToken,model.getMovieUrl());
            result.setSuccess(true);
            result.setErrMsg("");
            result.setData(movieList);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public AppV1Result movieTypeList(String keyWord,String uuid,String userToken) {
        AppV1Result result=new AppV1Result();
        try {
            if(CommonUtils.isBlank(uuid)){
                result.setSuccess(false);
                result.setErrMsg("设备uuid不能为空");
                return result;
            }
//            TbMovieUser user=movieUserMapper.selectByUserToken(userToken);
//            if(user==null){
//                result.setSuccess(false);
//                result.setErrMsg("用户参数不正确");
//                return result;
//            }
            TbMovie model=new TbMovie();
            if(CommonUtils.isNotBlank(keyWord)){
                model=JSON.parseObject(keyWord,TbMovie.class);
            }
            List<TbMovieType> movieTypeList=new ArrayList<>();
            List<TbMovie> movieList=movieMapper.selectMovieList(userToken,model.getMovieUrl());
            if(movieList.size()>0)
            {
                Map<String,String> movieMap=new HashMap<>();
                for(TbMovie movie:movieList)
                {
                    //恐怖,悬疑,惊悚
                    String movieType=movie.getMovieType();
                    String[] movieTypeArray=movieType.split(",");
                    if(movieTypeArray.length>0){
                        for(String type:movieTypeArray)
                        {
                            if(!movieMap.containsKey(type))
                            {
                                movieMap.put(type,type);
                            }
                        }
                    }
                }
                TbMovieType typeModelAll=new TbMovieType();
                typeModelAll.setTitle("全部");
                typeModelAll.setName("全部");
                typeModelAll.setList(movieList);
                movieTypeList.add(typeModelAll);
                for(Map.Entry<String, String> entry:movieMap.entrySet()){
                    String movieType=entry.getKey();
                    TbMovieType typeModel=new TbMovieType();
                    typeModel.setTitle(movieType);
                    typeModel.setName(movieType);
                    List<TbMovie> list=new ArrayList<>();
                    for(TbMovie movie:movieList){
                        if(movie.getMovieType().contains(movieType))
                        {
                            list.add(movie);
                        }
                    }
                    typeModel.setList(list);
                    movieTypeList.add(typeModel);
                }
            }
            result.setSuccess(true);
            result.setErrMsg("");
            result.setData(movieTypeList);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public AppV1Result shipList(String keyWord,String uuid) {
        AppV1Result result=new AppV1Result();
        try {
            if(CommonUtils.isBlank(uuid)){
                result.setSuccess(false);
                result.setErrMsg("设备uuid不能为空");
                return result;
            }
            result.setSuccess(true);
            result.setErrMsg("");
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public AppV1Result myMovie(String keyWord,String uuid,String userToken,String movieId) {
        AppV1Result result=new AppV1Result();
        try {
            if(CommonUtils.isBlank(uuid)){
                result.setSuccess(false);
                result.setErrMsg("设备uuid不能为空");
                return result;
            }
            TbMovie model=new TbMovie();
            if(CommonUtils.isNotBlank(keyWord)){
                model=JSON.parseObject(keyWord,TbMovie.class);
            }
            if(model.isNeedLogin()){
                TbMovieUser user=movieUserMapper.selectByUserToken(userToken);
                if(user==null){
                    result.setSuccess(false);
                    result.setErrMsg("未登录");
                    return result;
                }
            }else{
                userToken="0";
            }
            TbMovie movie=movieMapper.myMovie(userToken,movieId,model.getMovieUrl());
            result.setSuccess(true);
            result.setErrMsg("");
            result.setData(movie);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public AppV1Result myBill(String keyWord,String uuid,String userToken) {
        AppV1Result result=new AppV1Result();
        try {
            if(CommonUtils.isBlank(uuid)){
                result.setSuccess(false);
                result.setErrMsg("设备uuid不能为空");
                return result;
            }
            TbMovieUser user=movieUserMapper.selectByUserToken(userToken);
            if(user==null){
                result.setSuccess(false);
                result.setErrMsg("未登录");
                return result;
            }
            List<TbMovieUserBill> billList=movieUserBillMapper.myBill(userToken);
            //更新用户钱包金额
            BigDecimal walletAmount=movieUserService.statisticsWalletByUserId(userToken);
            Map<String,Object> map=new HashMap<>();
            map.put("billList",billList);
            map.put("walletAmount",walletAmount);
            result.setSuccess(true);
            result.setErrMsg("");
            result.setData(map);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public AppV1Result myCollect(String keyWord,String uuid,String userToken) {
        AppV1Result result=new AppV1Result();
        try {
            if(CommonUtils.isBlank(uuid)){
                result.setSuccess(false);
                result.setErrMsg("设备uuid不能为空");
                return result;
            }
            TbMovieUser user=movieUserMapper.selectByUserToken(userToken);
            if(user==null){
                result.setSuccess(false);
                result.setErrMsg("未登录");
                return result;
            }
            List<TbMovieCollectRecord> collectList=movieCollectRecordMapper.myCollect(userToken);
            if(collectList.size()>0)
            {
                for(TbMovieCollectRecord item:collectList){
                    if(item.getMovieType().equals("党建"))
                    {
                        item.setPosterLocalImg("../../../static/images/movie/default.jpg");
                    }
                }
            }
            result.setSuccess(true);
            result.setErrMsg("");
            result.setData(collectList);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public AppV1Result saveMyCollect(String keyWord, String uuid, String userToken) {
        AppV1Result result=new AppV1Result();
        try {
            if(CommonUtils.isBlank(uuid)){
                result.setSuccess(false);
                result.setErrMsg("设备uuid不能为空");
                return result;
            }
            TbMovieUser user=movieUserMapper.selectByUserToken(userToken);
            if(user==null){
                result.setSuccess(false);
                result.setErrMsg("未登录");
                return result;
            }
            TbMovieCollectRecord model=new TbMovieCollectRecord();
            if(CommonUtils.isNotBlank(keyWord)){
                model=JSON.parseObject(keyWord,TbMovieCollectRecord.class);
            }
            if(model==null){
                result.setSuccess(false);
                result.setErrMsg("参数错误");
                return result;
            }
            model.setUseStatus("normal");
            model.setCreateAdminId(0L);
            model.setCreateTime(new Date());
            String recordType=CommonUtils.parseStringData(model.getRecordType(),"del");
            if(recordType.equals("del")){
                movieCollectRecordMapper.delRecord(model.getMovieId(),userToken);
            }else{
                TbMovieCollectRecord record=movieCollectRecordMapper.getMovieCollectRecord(model.getMovieId(),userToken);
                if(record==null){
                    movieCollectRecordMapper.insert(model);
                }else{
                    model.setCollectRecordId(record.getCollectRecordId());
                    model.setUpdateAdminId(0L);
                    model.setUpdateTime(new Date());
                    movieCollectRecordMapper.updateByPrimaryKey(model);
                }
            }
            result.setSuccess(true);
            result.setErrMsg("");
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public AppV1Result myWatch(String keyWord,String uuid,String userToken) {
        AppV1Result result=new AppV1Result();
        try {
            if(CommonUtils.isBlank(uuid)){
                result.setSuccess(false);
                result.setErrMsg("设备uuid不能为空");
                return result;
            }
            TbMovieUser user=movieUserMapper.selectByUserToken(userToken);
            if(user==null){
                result.setSuccess(false);
                result.setErrMsg("未登录");
                return result;
            }
            List<TbMovieWatchRecord> watchList=movieWatchRecordMapper.myWatch(userToken);
            if(watchList.size()>0)
            {
                for(TbMovieWatchRecord item:watchList){
                    if(item.getMovieType().equals("党建"))
                    {
                        item.setPosterLocalImg("../../../static/images/movie/default.jpg");
                    }
                }
            }
            result.setSuccess(true);
            result.setErrMsg("");
            result.setData(watchList);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public AppV1Result saveMyWatch(String keyWord, String uuid, String userToken) {
        AppV1Result result=new AppV1Result();
        try {
            if(CommonUtils.isBlank(uuid)){
                result.setSuccess(false);
                result.setErrMsg("设备uuid不能为空");
                return result;
            }
            TbMovieUser user=movieUserMapper.selectByUserToken(userToken);
            if(user==null){
                result.setSuccess(false);
                result.setErrMsg("未登录");
                return result;
            }
            TbMovieWatchRecord model=new TbMovieWatchRecord();
            if(CommonUtils.isNotBlank(keyWord)){
                model=JSON.parseObject(keyWord,TbMovieWatchRecord.class);
            }
            if(model==null){
                result.setSuccess(false);
                result.setErrMsg("参数错误");
                return result;
            }
            model.setUseStatus("normal");
            model.setCreateAdminId(0L);
            model.setCreateTime(new Date());
            TbMovieWatchRecord record=movieWatchRecordMapper.getMovieWatchRecord(model.getMovieId(),userToken);
            if(record==null){
                movieWatchRecordMapper.insert(model);
            }else{
                model.setWatchRecordId(record.getWatchRecordId());
                model.setUpdateAdminId(0L);
                model.setUpdateTime(new Date());
                movieWatchRecordMapper.updateByPrimaryKey(model);
            }
            result.setSuccess(true);
            result.setErrMsg("");
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public AppV1Result myBuy(String keyWord,String uuid,String userToken) {
        AppV1Result result=new AppV1Result();
        try {
            if(CommonUtils.isBlank(uuid)){
                result.setSuccess(false);
                result.setErrMsg("设备uuid不能为空");
                return result;
            }
            TbMovieUser user=movieUserMapper.selectByUserToken(userToken);
            if(user==null){
                result.setSuccess(false);
                result.setErrMsg("未登录");
                return result;
            }
            List<TbMovieUserBill> billList=movieUserBillMapper.myBill(userToken);
            //更新用户钱包金额
            BigDecimal walletAmount=movieUserService.statisticsWalletByUserId(userToken);
            Map<String,Object> map=new HashMap<>();
            map.put("billList",billList);
            map.put("walletAmount",walletAmount);
            result.setSuccess(true);
            result.setErrMsg("");
            result.setData(map);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public AppV1Result myLike(String keyWord,String uuid,String userToken) {
        AppV1Result result=new AppV1Result();
        try {
            if(CommonUtils.isBlank(uuid)){
                result.setSuccess(false);
                result.setErrMsg("设备uuid不能为空");
                return result;
            }
            TbMovieUser user=movieUserMapper.selectByUserToken(userToken);
            if(user==null){
                result.setSuccess(false);
                result.setErrMsg("未登录");
                return result;
            }
            List<TbMovieLikeRecord> likeList=movieLikeRecordMapper.myLike(userToken);
            if(likeList.size()>0)
            {
                for(TbMovieLikeRecord item:likeList){
                    if(item.getMovieType().equals("党建"))
                    {
                        item.setPosterLocalImg("../../../static/images/movie/default.jpg");
                    }
                }
            }
            result.setSuccess(true);
            result.setErrMsg("");
            result.setData(likeList);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public AppV1Result saveMyLike(String keyWord, String uuid, String userToken) {
        AppV1Result result=new AppV1Result();
        try {
            if(CommonUtils.isBlank(uuid)){
                result.setSuccess(false);
                result.setErrMsg("设备uuid不能为空");
                return result;
            }
            TbMovieUser user=movieUserMapper.selectByUserToken(userToken);
            if(user==null){
                result.setSuccess(false);
                result.setErrMsg("未登录");
                return result;
            }
            TbMovieLikeRecord model=new TbMovieLikeRecord();
            if(CommonUtils.isNotBlank(keyWord)){
                model=JSON.parseObject(keyWord,TbMovieLikeRecord.class);
            }
            if(model==null){
                result.setSuccess(false);
                result.setErrMsg("参数错误");
                return result;
            }
            model.setUseStatus("normal");
            model.setCreateAdminId(0L);
            model.setCreateTime(new Date());
            String recordType=CommonUtils.parseStringData(model.getRecordType(),"del");
            if(recordType.equals("del")){
                movieLikeRecordMapper.delRecord(model.getMovieId(),userToken);
            }else{
                TbMovieLikeRecord record=movieLikeRecordMapper.getMovieLikeRecord(model.getMovieId(),userToken);
                if(record==null){
                    movieLikeRecordMapper.insert(model);
                }else{
                    model.setLikeRecordId(record.getLikeRecordId());
                    model.setUpdateAdminId(0L);
                    model.setUpdateTime(new Date());
                    movieLikeRecordMapper.updateByPrimaryKey(model);
                }
            }

            result.setSuccess(true);
            result.setErrMsg("");
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }


    @Override
    public AppV1Result rechargeWallet(String keyWord,String uuid,String userToken,BigDecimal amount) {
        AppV1Result result=new AppV1Result();
        try {
            result.setSuccess(false);
            result.setErrMsg("船端服务禁止充值服务！");
//            if(CommonUtils.isBlank(uuid)){
//                result.setSuccess(false);
//                result.setErrMsg("设备uuid不能为空");
//                return result;
//            }
//
//            if(amount==null){
//                result.setSuccess(false);
//                result.setErrMsg("充值金额不能为空");
//                return result;
//            }
//            Integer totalFee=(int)(CommonUtils.parseDoubleData(amount.setScale(2))*100);
//            if(totalFee<=0)
//            {
//                result.setSuccess(false);
//                result.setErrMsg("充值金额错误");
//                return result;
//            }
//            TbMovieUser user=movieUserMapper.selectByMovieUserId(movieUserId);
//            if(user==null){
//                result.setSuccess(false);
//                result.setErrMsg("账户错误，请重新登录");
//                return result;
//            }
//            result.setSuccess(false);
//            result.setErrMsg("船端不能充值，请切换到岸端服务器");
//            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }


    @Override
    public AppV1Result purchaseMovie(String uuid, String userToken, String movieId) {
        AppV1Result result=new AppV1Result();
        try {
            if(CommonUtils.isBlank(uuid)){
                result.setSuccess(false);
                result.setErrMsg("设备uuid不能为空");
                return result;
            }
            TbMovieUser movieUser=movieUserMapper.selectByUserToken(userToken);
            if(movieUser==null){
                result.setSuccess(false);
                result.setErrMsg("未登录");
                return result;
            }
            TbMovie movie=movieMapper.selectMovieByMovieId(movieId,"");
            if(movie==null){
                result.setSuccess(false);
                result.setErrMsg("影片不存在");
                return result;
            }
            int movieAmountResult = movie.getAmount().compareTo(BigDecimal.ZERO);
            if(movieAmountResult>0){
                List<TbMovieUserBill> billList=movieUserBillMapper.selectByUserIdAndMovieId(userToken,movieId);
                if(billList.size()==0)
                {
                    /**
                     * 1、检查钱包是否有金币
                     */
                    int walletAmountResult = movieUser.getWalletAmount().compareTo(movie.getAmount());
                    if(walletAmountResult<0)
                    {
                        result.setSuccess(false);
                        result.setErrMsg("钱包金币不足，请充值");
                        return result;
                    }
                    /**
                     * 2、下单
                     */
                    BigDecimal movieAmount=movie.getAmount().negate();
                    TbMovieUserBill model=new TbMovieUserBill();
                    model.setBillType("out");
                    model.setDataResource("ship");
                    model.setOrderFlag(1);
                    String orderNo= DateUtils.format(new Date(), DateUtils.YMD_DASH_WITH_MITIME_STR);
                    model.setOrderNo(orderNo);
                    model.setShipId(movieUser.getShipId());
                    model.setShipName(movieUser.getShipName());
                    model.setMovieId(movie.getMovieId());
                    model.setUuid(UUID.randomUUID().toString().replaceAll("-","").toLowerCase());
                    model.setMovieUserId(movieUser.getMovieUserId());
                    model.setUserToken(movieUser.getUserToken());
                    model.setOpenid(movieUser.getOpenid());
                    model.setTrueName(movieUser.getTrueName());
                    model.setMobile(movieUser.getMobile());
                    model.setTotalFee(movieAmount.multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP).intValue());
                    model.setDisplayName(movie.getDisplayName());
                    model.setBillAmount(movieAmount);
                    model.setOrderNotifyDate(new Date());
                    model.setUseStatus("normal");
                    model.setCreateAdminId(0L);
                    model.setCreateTime(new Date());
                    movieUserBillMapper.insert(model);
                    result.setSuccess(true);
                    result.setErrMsg("购买成功");
                    result.setData(model);
                }else{
                    result.setSuccess(true);
                    result.setErrMsg("您已购买该影片，无需再购买");
                }
            }else{
                result.setSuccess(true);
                result.setErrMsg("免费观看");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public AppV1Result getPlayUrl(String uuid, String userToken, String movieId,String keyWord,boolean needLogin) {
        AppV1Result result=new AppV1Result();
        String url="";
        boolean success=false;
        String errMsg="获取播放地址失败";
        try {
            if(CommonUtils.isBlank(uuid)){
                result.setSuccess(false);
                result.setErrMsg("设备uuid不能为空");
                return result;
            }
            if(CommonUtils.isNotBlank(keyWord)){
                TbMovie model=JSON.parseObject(keyWord,TbMovie.class);
                needLogin=model.isNeedLogin();
            }
            if(needLogin){
                TbMovieUser movieUser=movieUserMapper.selectByUserToken(userToken);
                if(movieUser==null){
                    result.setSuccess(false);
                    result.setErrMsg("未登录");
                    return result;
                }
            }
            TbMovie movie=movieMapper.selectMovieByMovieId(movieId,"");
            if(movie==null){
                result.setSuccess(false);
                result.setErrMsg("影片不存在");
                return result;
            }
            TbMovieServer movieServer = new TbMovieServer();
            List<TbMovieServer> list = movieServerMapper.selectListBySQL(movieServer);
            if (list.size() > 0) {
                String shipServerUrl = list.get(0).getServerUrl();
                Map<String, Object> regitsterDeviceParams = new LinkedHashMap<>();
                /**
                 * {
                 * 	"C": "Device",
                 * "D": {
                 * "IP": "192.168.1.1",
                 * "MAC": "DD:DD:DD:DD:DD:DD",
                 * "ModelNo": "BOX-002",
                 * "Title": "BOX-002",
                 * "UniqueCode": "b562e3d8a4314e9e9ae6c3648855b2e2",
                 * "Version": 1.23
                 * },
                 * "F": "Regdevice",
                 * "M": "DD:DD:DD:DD:DD:DD",
                 * "U": "b562e3d8a4314e9e9ae6c3648855b2e2"
                 * }
                 */
                String uuidMac="";
                if(uuid.length()<12)
                {
                    uuidMac=UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
                }else{
                    uuidMac=uuid.toUpperCase();
                }
                String mac=uuidMac.substring(0,2)+":"+uuidMac.substring(2,4)+":"+uuidMac.substring(4,6)+":"+uuidMac.substring(6,8)+":"+uuidMac.substring(8,10)+":"+uuidMac.substring(10,12);
                regitsterDeviceParams.put("C", "Device");
                Map<String, Object> D = new LinkedHashMap<>();
                D.put("IP", "192.168.1.1");
                D.put("MAC", mac);
                D.put("ModelNo", "BOX-001");
                D.put("Title", "BOX-001");
                D.put("UniqueCode", uuid);
                D.put("Version", 1.23);
                regitsterDeviceParams.put("D", D);
                regitsterDeviceParams.put("F", "Regdevice");
                regitsterDeviceParams.put("M", mac);
                regitsterDeviceParams.put("U", uuid);
                String regitsterDeviceShipServerResult = ystMovieService.getRegitsterDeviceShipServer(shipServerUrl, regitsterDeviceParams);
                log.info("regitsterDeviceShipServerResult=="+regitsterDeviceShipServerResult);
                if (CommonUtils.isNotBlank(regitsterDeviceShipServerResult)) {
                    Map<String, Object> getPlayUrlParams = new LinkedHashMap<>();
                    getPlayUrlParams.put("mac", mac);
                    getPlayUrlParams.put("filmsource", "2");
                    getPlayUrlParams.put("movieId",movieId);
                    String getPlayUrlResult = ystMovieService.getPlayUrlByShipServer(shipServerUrl, getPlayUrlParams);
                    if (CommonUtils.isNotBlank(getPlayUrlResult)) {
                        YstMovieResult getPlayUrlData = JSON.parseObject(getPlayUrlResult, YstMovieResult.class);
                        if (getPlayUrlData != null && getPlayUrlData.isState()) {
                            Map<String,Object> getPlayUrlDataMap= (Map<String, Object>) getPlayUrlData.getData();
                            if(getPlayUrlDataMap.containsKey("Url")){
                                url=CommonUtils.parseStringData(getPlayUrlDataMap.get("Url"));
                                log.info("Url=="+url);
                                success=true;
                                errMsg="获取播放地址成功";
                            }else{
                                errMsg="在影视服务器获取url数据解析Url失败";
                            }
                        }else{
                            String info=CommonUtils.parseStringData(getPlayUrlData.getInfo());
                            errMsg="在影视服务器获取url数据解析Url失败";
                            log.info("在影视服务器获取url数据解析Url失败："+getPlayUrlResult);
                            if(CommonUtils.isNotBlank(info)){
                                errMsg=info+"，请联系技术人员";
                            }                        }
                    }else{
                        errMsg="在影视服务器获取url失败";
                    }
                }else{
                    errMsg="设备在影视服务器注册失败";
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            errMsg="连接不上影视服务器";
        }
        result.setSuccess(success);
        result.setErrMsg(errMsg);
        result.setData(url);
        log.info("result=="+JSON.toJSONString(result));
        return result;
    }

    @Override
    public AppV1Result updatePwd(String uuid, String userToken, String password, String newPassword) {
        AppV1Result result=new AppV1Result();
        boolean success=false;
        String errMsg="操作失败";
        try {
            if(CommonUtils.isBlank(uuid)){
                result.setSuccess(false);
                result.setErrMsg("设备uuid不能为空");
                return result;
            }
            TbMovieUser movieUser=movieUserMapper.selectByUserToken(userToken);
            if(movieUser==null){
                result.setSuccess(false);
                result.setErrMsg("未登录");
                return result;
            }
            if(CommonUtils.isBlank(newPassword)){
                result.setSuccess(false);
                result.setErrMsg("新密码不能为空");
                return result;
            }
            if(movieUser.getPassword().equals(password))
            {
                movieUserMapper.updatePassword(userToken,newPassword);
                success=true;
                errMsg="";
            }else{
                result.setSuccess(false);
                result.setErrMsg("旧密码不正确");
                return result;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        result.setSuccess(success);
        result.setErrMsg(errMsg);
        return result;
    }

    @Override
    public void showMovieImg(String filePath, HttpServletRequest request, HttpServletResponse response) {
        BufferedInputStream bis = null;
        ByteArrayOutputStream out = null;
        String imagePath=movieDir+File.separator+filePath;
        try {
            String exName= FileUtils.getExtend(imagePath).toLowerCase();
            if(exName.equals("jpg") || exName.equals("jpeg") || exName.equals("png")) {
                File file = new File(imagePath);
                if(!file.exists()){
                    return;
                }
                FileInputStream iputStream = new FileInputStream(file);
                bis = new BufferedInputStream(iputStream, 1024);
                out = new ByteArrayOutputStream();
                byte[] bytes = new byte[1024];
                int len;
                while ((len = bis.read(bytes)) > 0) {
                    out.write(bytes, 0, len);
                }
                response.setCharacterEncoding("UTF-8");
                if (request.getHeader("User-agent").contains("MSIE")) {
                    response.setHeader("Content-Disposition",
                            String.format("inline;filename=%s", URLEncoder.encode("title", "UTF-8")));
                }
                else {
                    response.setHeader("Content-Disposition",
                            String.format("inline;filename=\"%s\"", new String("title".getBytes("UTF-8"), "ISO8859-1")));
                }
                out.writeTo(response.getOutputStream());
            }else {
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().print("<div style=\"font-size: 30px;color:red;margin-top: 120px;text-align: center;\">参数含有非法攻击字符,已禁止继续访问！</div>");
            }
        } catch (Exception e) {
//            log.error(e.getMessage(),e);
        } finally {
            try {
                if(bis!=null) {
                    bis.close();
                }
                if(out!=null)
                {
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                //e.printStackTrace();
            }
        }
    }

    @Override
    public AppV1Result showMovieImgBase64(String filePath, HttpServletRequest request, HttpServletResponse response) {
        AppV1Result result=new AppV1Result();
        boolean success=false;
        String errMsg="操作失败";
        String data="";
        String imagePath=movieDir+File.separator+filePath;
        try {
            String exName= FileUtils.getExtend(imagePath).toLowerCase();
            if(exName.equals("jpg") || exName.equals("jpeg") || exName.equals("png")) {
                File file = new File(imagePath);
                data=ImageToBase64Converter.convertToBase64(file);
                success=true;
                errMsg="";
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        result.setSuccess(success);
        result.setData(data);
        result.setErrMsg(errMsg);
        return result;
    }

    @Override
    public AppV1Result flowDataList(String keyWord, String uuid, String userToken) {
        AppV1Result result=new AppV1Result();
        try {
            if(CommonUtils.isBlank(uuid)){
                result.setSuccess(false);
                result.setErrMsg("设备uuid不能为空");
                return result;
            }
            TbMovieUser user=movieUserMapper.selectByUserToken(userToken);
            if(user==null){
                result.setSuccess(false);
                result.setErrMsg("用户参数不正确");
                return result;
            }
            TbProductInfo model=new TbProductInfo();
            if(CommonUtils.isNotBlank(keyWord)){
                model=JSON.parseObject(keyWord,TbProductInfo.class);
            }
            model.setProductType("1");
            model.setSellFlag(1);
            List<TbProductInfo> productList=productInfoMapper.selectListBySQL(model);
            result.setSuccess(true);
            result.setErrMsg("");
            result.setData(productList);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public AppV1Result broadDataList(String keyWord, String uuid, String userToken) {
        AppV1Result result=new AppV1Result();
        try {
            if(CommonUtils.isBlank(uuid)){
                result.setSuccess(false);
                result.setErrMsg("设备uuid不能为空");
                return result;
            }
            TbMovieUser user=movieUserMapper.selectByUserToken(userToken);
            if(user==null){
                result.setSuccess(false);
                result.setErrMsg("用户参数不正确");
                return result;
            }
            TbProductInfo model=new TbProductInfo();
            if(CommonUtils.isNotBlank(keyWord)){
                model=JSON.parseObject(keyWord,TbProductInfo.class);
            }
            model.setProductType("2");
            model.setSellFlag(1);
            List<TbProductInfo> productList=productInfoMapper.selectListBySQL(model);
            result.setSuccess(true);
            result.setErrMsg("");
            result.setData(productList);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public AppV1Result purchaseFlowOrBroadData(String uuid, String userToken, String keyWord) {
        AppV1Result result=new AppV1Result();
        try {
            if(CommonUtils.isBlank(uuid)){
                result.setSuccess(false);
                result.setErrMsg("设备uuid不能为空");
                return result;
            }
            if(CommonUtils.isBlank(keyWord)){
                result.setSuccess(false);
                result.setErrMsg("参数不能为空");
                return result;
            }
            TbMovieUser movieUser=movieUserMapper.selectByUserToken(userToken);
            if(movieUser==null){
                result.setSuccess(false);
                result.setErrMsg("未登录");
                return result;
            }
            TbMovieUserBill bill=JSON.parseObject(keyWord,TbMovieUserBill.class);
            if(bill==null){
                result.setSuccess(false);
                result.setErrMsg("参数不能为空");
                return result;
            }
            if(CommonUtils.isBlank(bill.getUserAccount())){
                result.setSuccess(false);
                result.setErrMsg("充值账号不能为空");
                return result;
            }
            if(CommonUtils.isBlank(bill.getUserPassword())){
                result.setSuccess(false);
                result.setErrMsg("充值密码不能为空");
                return result;
            }
            if(CommonUtils.isBlank(bill.getRemark())){
                result.setSuccess(false);
                result.setErrMsg("购买备注不能为空");
                return result;
            }
            String productUuid=bill.getProductUUid();
            TbProductInfo productInfo=productInfoMapper.getByUUId(productUuid);
            if(productInfo==null){
                result.setSuccess(false);
                result.setErrMsg("产品不存在");
                return result;
            }
            if(productInfo.getProductPrice()>0){
                    /**
                     * 1、检查钱包是否有金币
                     */
                    BigDecimal walletAmount = MathUtils.multiply(movieUser.getWalletAmount(),new BigDecimal(100));
                    int walletAmountResult=walletAmount.intValue();
                    if(walletAmountResult<productInfo.getProductPrice())
                    {
                        result.setSuccess(false);
                        result.setErrMsg("钱包金币不足，请充值");
                        return result;
                    }
                    /**
                     * 2、下单
                     */
                    BigDecimal movieAmount=MathUtils.divide(new BigDecimal(productInfo.getProductPrice()),new BigDecimal(100),2);
                    TbMovieUserBill model=new TbMovieUserBill();
                    model.setBillType("out");
                    model.setDataResource("ship");
                    model.setDataType(productInfo.getProductType().equals("1")?"flow":"broad");
                    model.setOrderFlag(1);
                    String orderNo= DateUtils.format(new Date(), DateUtils.YMD_DASH_WITH_MITIME_STR);
                    model.setOrderNo(orderNo);
                    model.setShipId(movieUser.getShipId());
                    model.setShipName(movieUser.getShipName());

                    model.setUuid(UUID.randomUUID().toString().replaceAll("-","").toLowerCase());
                    model.setMovieUserId(movieUser.getMovieUserId());
                    model.setUserToken(movieUser.getUserToken());
                    model.setOpenid(movieUser.getOpenid());
                    model.setTrueName(movieUser.getTrueName());
                    model.setMobile(movieUser.getMobile());
                    Integer totalFee=movieAmount.multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
                    model.setTotalFee(totalFee);
                    model.setBillAmount(movieAmount.negate());
                    model.setUseStatus("normal");
                    model.setCreateAdminId(0L);
                    model.setCreateTime(new Date());
                    model.setOrderNotifyDate(new Date());

                    model.setUserAccount(bill.getUserAccount());
                    model.setUserPassword(bill.getUserPassword());
                    model.setRemark(bill.getRemark());
                    model.setHandleFlag(0);
                    model.setProductUUid(productInfo.getUuid());
                    model.setProductId(productInfo.getProductId());
                    model.setProductQuantity(productInfo.getProductQuantity());
                    model.setProductName(productInfo.getProductName());
                    movieUserBillMapper.insert(model);
                    result.setSuccess(true);
                    result.setErrMsg("购买成功");
                    result.setData(model);
            }else{
                result.setSuccess(true);
                result.setErrMsg("您的产品不需要购买");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public AppV1Result getSailasTVInfo(String uuid, String userToken, boolean needLogin,String androidType) {
        AppV1Result result=new AppV1Result();
        try {
            TbSailasTVClient client=new TbSailasTVClient();
            if(CommonUtils.isBlank(uuid)){
                result.setSuccess(false);
                result.setErrMsg("设备uuid不能为空");
                return result;
            }
            if(CommonUtils.isBlank(androidType)){
                androidType="tv";
            }
            TbAndroidDevice device=new TbAndroidDevice();
            device.setAndroidUuid(uuid);
            List<TbAndroidDevice> deviceList=androidDeviceMapper.selectListBySQL(device);
            if(deviceList.size()==0){
                device.setAndroidType(androidType);
                device.setUseStatus("normal");
                device.setCreateAdminId(0L);
                device.setCreateTime(new Date());
                androidDeviceMapper.insert(device);
            }else{
                device=deviceList.get(0);
                client.setUserKey(CommonUtils.isNotBlank(device.getUserKey())?device.getUserKey():"");
            }

            TbMovieServer server=new TbMovieServer();
            List<TbMovieServer> serverList=movieServerMapper.selectListBySQL(server);
            if(serverList.size()>0){
                server=serverList.get(0);
                client.setClientId(CommonUtils.isNotBlank(server.getSailastvClientId())?server.getSailastvClientId():"");
                client.setClientSecret(CommonUtils.isNotBlank(server.getSailastvClientSecret())?server.getSailastvClientSecret():"");
            }
//            client.setClientId("2nuvs7c0gu7rn9ijtclt7t9p6g");
//            client.setClientSecret("16jrnnb7imt6t7hlggbfqlqnve1h1qmb5kf2m4fb5qabflkaetnl");
//            client.setUserKey("hEdwrSA45twPqXpS4ubrNK");
            result.setSuccess(true);
            result.setErrMsg("");
            result.setData(client);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }


}
